// 购物车状态管理

import { defineStore } from 'pinia'
import type { CartItem, Product, ProductSku } from '@/types/mall'
import { calculateCartTotal, generateId } from '@/utils/mall'
import { STORAGE_KEYS, MAX_CART_QUANTITY } from '@/constants/mall'

interface CartState {
  items: CartItem[]
  loading: boolean
  lastUpdateTime: string
}

export const useCartStore = defineStore('cart', {
  state: (): CartState => ({
    items: [],
    loading: false,
    lastUpdateTime: new Date().toISOString(),
  }),

  getters: {
    // 购物车商品总数量
    totalQuantity(): number {
      return this.items.reduce((sum, item) => sum + item.quantity, 0)
    },

    // 购物车商品总价
    totalPrice(): number {
      return this.items.reduce((sum, item) => {
        const price = item.sku?.price || item.product.defaultPrice
        return sum + price * item.quantity
      }, 0)
    },

    // 选中商品数量
    selectedQuantity(): number {
      return this.items
        .filter(item => item.selected)
        .reduce((sum, item) => sum + item.quantity, 0)
    },

    // 选中商品总价
    selectedPrice(): number {
      return this.items
        .filter(item => item.selected)
        .reduce((sum, item) => {
          const price = item.sku?.price || item.product.defaultPrice
          return sum + price * item.quantity
        }, 0)
    },

    // 选中的商品列表
    selectedItems(): CartItem[] {
      return this.items.filter(item => item.selected)
    },

    // 是否全选
    isAllSelected(): boolean {
      return this.items.length > 0 && this.items.every(item => item.selected)
    },

    // 购物车是否为空
    isEmpty(): boolean {
      return this.items.length === 0
    },

    // 获取商品在购物车中的数量
    getProductQuantity(): (productId: string, skuId?: string) => number {
      return (productId: string, skuId?: string) => {
        const item = this.items.find(item => 
          item.productId === productId && 
          (skuId ? item.skuId === skuId : !item.skuId)
        )
        return item?.quantity || 0
      }
    },

    // 检查商品是否在购物车中
    hasProduct(): (productId: string, skuId?: string) => boolean {
      return (productId: string, skuId?: string) => {
        return this.items.some(item => 
          item.productId === productId && 
          (skuId ? item.skuId === skuId : !item.skuId)
        )
      }
    },
  },

  actions: {
    // 初始化购物车（从本地存储加载）
    async initCart() {
      try {
        const savedCart = uni.getStorageSync(STORAGE_KEYS.CART_DATA)
        if (savedCart) {
          const cartData = JSON.parse(savedCart)
          this.items = cartData.items || []
          this.lastUpdateTime = cartData.lastUpdateTime || new Date().toISOString()
        }
      } catch (error) {
        console.error('Failed to load cart from storage:', error)
        this.items = []
      }
    },

    // 保存购物车到本地存储
    saveCart() {
      try {
        const cartData = {
          items: this.items,
          lastUpdateTime: this.lastUpdateTime,
        }
        uni.setStorageSync(STORAGE_KEYS.CART_DATA, JSON.stringify(cartData))
      } catch (error) {
        console.error('Failed to save cart to storage:', error)
      }
    },

    // 添加商品到购物车
    async addToCart(
      product: Product, 
      sku?: ProductSku, 
      quantity = 1
    ): Promise<boolean> {
      try {
        this.loading = true

        // 检查商品状态
        if (product.status !== 'active') {
          uni.showToast({ title: '商品已下架', icon: 'none' })
          return false
        }

        // 检查库存
        const stock = sku?.stock || product.stock
        if (stock <= 0) {
          uni.showToast({ title: '商品库存不足', icon: 'none' })
          return false
        }

        // 查找现有商品项
        const existingItemIndex = this.items.findIndex(item => 
          item.productId === product.id && 
          (sku ? item.skuId === sku.id : !item.skuId)
        )

        if (existingItemIndex >= 0) {
          // 更新现有商品数量
          const existingItem = this.items[existingItemIndex]
          const newQuantity = existingItem.quantity + quantity

          if (newQuantity > stock) {
            uni.showToast({ title: '超出库存限制', icon: 'none' })
            return false
          }

          if (newQuantity > MAX_CART_QUANTITY) {
            uni.showToast({ title: `单个商品最多添加${MAX_CART_QUANTITY}件`, icon: 'none' })
            return false
          }

          existingItem.quantity = newQuantity
        } else {
          // 添加新商品项
          if (quantity > stock) {
            uni.showToast({ title: '超出库存限制', icon: 'none' })
            return false
          }

          const newItem: CartItem = {
            id: generateId('cart_'),
            productId: product.id,
            skuId: sku?.id,
            product,
            sku,
            quantity,
            selected: true,
            addedAt: new Date().toISOString(),
          }

          this.items.unshift(newItem)
        }

        this.lastUpdateTime = new Date().toISOString()
        this.saveCart()

        uni.showToast({ title: '已添加到购物车', icon: 'success' })
        return true
      } catch (error) {
        console.error('Failed to add to cart:', error)
        uni.showToast({ title: '添加失败，请重试', icon: 'none' })
        return false
      } finally {
        this.loading = false
      }
    },

    // 更新购物车商品数量
    async updateQuantity(itemId: string, quantity: number): Promise<boolean> {
      try {
        const item = this.items.find(item => item.id === itemId)
        if (!item) {
          uni.showToast({ title: '商品不存在', icon: 'none' })
          return false
        }

        if (quantity <= 0) {
          return this.removeItem(itemId)
        }

        const stock = item.sku?.stock || item.product.stock
        if (quantity > stock) {
          uni.showToast({ title: '超出库存限制', icon: 'none' })
          return false
        }

        if (quantity > MAX_CART_QUANTITY) {
          uni.showToast({ title: `单个商品最多添加${MAX_CART_QUANTITY}件`, icon: 'none' })
          return false
        }

        item.quantity = quantity
        this.lastUpdateTime = new Date().toISOString()
        this.saveCart()

        return true
      } catch (error) {
        console.error('Failed to update quantity:', error)
        return false
      }
    },

    // 删除购物车商品
    async removeItem(itemId: string): Promise<boolean> {
      try {
        const index = this.items.findIndex(item => item.id === itemId)
        if (index >= 0) {
          this.items.splice(index, 1)
          this.lastUpdateTime = new Date().toISOString()
          this.saveCart()
          return true
        }
        return false
      } catch (error) {
        console.error('Failed to remove item:', error)
        return false
      }
    },

    // 切换商品选中状态
    toggleItemSelect(itemId: string) {
      const item = this.items.find(item => item.id === itemId)
      if (item) {
        item.selected = !item.selected
        this.lastUpdateTime = new Date().toISOString()
        this.saveCart()
      }
    },

    // 设置商品选中状态
    setItemSelect(itemId: string, selected: boolean) {
      const item = this.items.find(item => item.id === itemId)
      if (item) {
        item.selected = selected
        this.lastUpdateTime = new Date().toISOString()
        this.saveCart()
      }
    },

    // 全选/取消全选
    toggleSelectAll() {
      const selectAll = !this.isAllSelected
      this.items.forEach(item => {
        item.selected = selectAll
      })
      this.lastUpdateTime = new Date().toISOString()
      this.saveCart()
    },

    // 清空购物车
    async clearCart(): Promise<boolean> {
      try {
        this.items = []
        this.lastUpdateTime = new Date().toISOString()
        this.saveCart()
        return true
      } catch (error) {
        console.error('Failed to clear cart:', error)
        return false
      }
    },

    // 清空选中的商品
    async clearSelectedItems(): Promise<boolean> {
      try {
        this.items = this.items.filter(item => !item.selected)
        this.lastUpdateTime = new Date().toISOString()
        this.saveCart()
        return true
      } catch (error) {
        console.error('Failed to clear selected items:', error)
        return false
      }
    },

    // 刷新购物车（从服务器同步）
    async refreshCart(): Promise<boolean> {
      try {
        this.loading = true
        // TODO: 从服务器获取购物车数据
        // const response = await api.cart.getCartList()
        // this.items = response.data
        this.lastUpdateTime = new Date().toISOString()
        this.saveCart()
        return true
      } catch (error) {
        console.error('Failed to refresh cart:', error)
        return false
      } finally {
        this.loading = false
      }
    },

    // 同步购物车到服务器
    async syncCart(): Promise<boolean> {
      try {
        // TODO: 同步购物车到服务器
        // await api.cart.syncCart(this.items)
        return true
      } catch (error) {
        console.error('Failed to sync cart:', error)
        return false
      }
    },
  },

  // 开启持久化
  persist: {
    enabled: true,
    strategies: [
      {
        key: STORAGE_KEYS.CART_DATA,
        storage: {
          getItem: (key: string) => uni.getStorageSync(key),
          setItem: (key: string, value: string) => uni.setStorageSync(key, value),
          removeItem: (key: string) => uni.removeStorageSync(key),
        },
      },
    ],
  },
})